import './teacher.scss'
import {
  Table,
  Dropdown,
  Space,
  message,
  Card,
  Input,
  ConfigProvider,
  Button,
  Modal,
  Form,
} from 'antd'
import { DownOutlined, UsergroupAddOutlined } from '@ant-design/icons'
import { css } from '@emotion/css'
import { reqAdminAddTeacher } from '@/api/admin'

import {
  reqAdminGetAllTeacher,
  reqAdminChangeTeacherLimit,
  reqAdminChangeTeacherModel,
} from '@/api/admin'
import { useEffect, useState, useContext } from 'react'
function Teacher() {
  // 教师数据
  const [teacherList, setTeacherList] = useState([])
  // 添加教师对话框的显示与隐藏
  const [isModalOpen, setIsModalOpen] = useState(false)
  // 表单数据
  const [formData, setFormData] = useState({
    username: '',
    password: '',
  })
  const [form] = Form.useForm()

  const items = (record: any, who: any) => [
    {
      key: '1',
      label: <div onClick={() => onClick('1', record, who)}>允许</div>,
    },
    {
      key: '0',
      label: <div onClick={() => onClick('0', record, who)}>拒绝</div>,
    },
  ]

  const onClick = (key: any, record: any, who: any) => {
    console.log(key, record, who)
    if (who === 'modullimits') {
      changeTeacherModel(record.id, key)
    } else if (who === 'classlimits') {
      changeTeacherLimit(record.id, key)
    }
  }

  const columns: any = [
    {
      title: '教师ID',
      width: 100,
      align: 'center',
      ellipsis: true,
      dataIndex: 'id',
    },
    {
      title: '名称',
      align: 'center',
      ellipsis: true,
      dataIndex: 'username',
    },
    {
      title: '密码',
      align: 'center',
      ellipsis: true,
      dataIndex: 'password',
    },
    {
      title: '封禁学生模块权限',
      align: 'center',
      ellipsis: true,
      dataIndex: 'modullimits',
      render: (text: any, record: any) => (
        <Dropdown menu={{ items: items(record, 'modullimits') }}>
          <a onClick={(e) => e.preventDefault()}>
            <Space>
              {text === 1 ? '有' : '无'}
              <DownOutlined />
            </Space>
          </a>
        </Dropdown>
      ),
    },
    {
      title: '添加选课权限',
      align: 'center',
      ellipsis: true,
      dataIndex: 'classlimits',
      render: (text: any, record: any) => (
        <Dropdown menu={{ items: items(record, 'classlimits') }}>
          <a onClick={(e) => e.preventDefault()}>
            <Space>
              {text === 1 ? '有' : '无'}
              <DownOutlined />
            </Space>
          </a>
        </Dropdown>
      ),
    },
  ]

  // 获取全部教师
  const getAllTeacher = async () => {
    const res: any = await reqAdminGetAllTeacher()
    if (res.code === 200) {
      setTeacherList(res.data)
    }
  }

  // 更改教师选课权限
  const changeTeacherLimit = async (id: number, num: number) => {
    const res: any = await reqAdminChangeTeacherLimit({ id, classlimits: num })
    if (res.code === 200) {
      message.success('更改成功')
      getAllTeacher()
    } else {
      message.error('更改失败')
    }
  }

  // 更改教师模型权限
  const changeTeacherModel = async (id: number, num: number) => {
    const res: any = await reqAdminChangeTeacherModel({ id, modullimits: num })
    if (res.code === 200) {
      message.success('更改成功')
      getAllTeacher()
    } else {
      message.error('更改失败')
    }
  }

  useEffect(() => {
    getAllTeacher()
  }, [])

  // 按钮的配置
  const { getPrefixCls } = useContext(ConfigProvider.ConfigContext)
  const rootPrefixCls = getPrefixCls()
  const linearGradientButton = css`
    &.${rootPrefixCls}-btn-primary:not([disabled]):not(.${rootPrefixCls}-btn-dangerous) {
      border-width: 0;

      > span {
        position: relative;
      }

      &::before {
        content: '';
        background: linear-gradient(135deg, #6253e1, #04befe);
        position: absolute;
        inset: 0;
        opacity: 1;
        transition: all 0.3s;
        border-radius: inherit;
      }

      &:hover::before {
        opacity: 0;
      }
    }
  `

  // 点击添加教师按钮的回调
  const handleAddTeacher = () => {
    form.resetFields()
    setIsModalOpen(true)
  }

  // 点击确定添加教师按钮的回调
  const handleOk = async () => {
    await form.validateFields()
    const res: any = await reqAdminAddTeacher(formData)
    if (res.code === 200) {
      getAllTeacher()
      message.success('添加成功')
    } else {
      message.error('添加失败')
    }
    setIsModalOpen(false)
  }

  return (
    <div className="Teacher">
      <ConfigProvider
        button={{
          className: linearGradientButton,
        }}
      >
        <Button
          style={{ marginBottom: '10px' }}
          type="primary"
          size="large"
          onClick={handleAddTeacher}
          icon={<UsergroupAddOutlined />}
        >
          添加教师
        </Button>
      </ConfigProvider>
      <Card>
        <Table
          dataSource={teacherList}
          columns={columns}
          pagination={false}
          rowKey={(record: any) => record.id}
        />
      </Card>
      <Modal
        title="添加教师"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={() => setIsModalOpen(false)}
      >
        <Form
          form={form}
          name="basic"
          size="large"
          style={{ marginTop: '20px' }}
          initialValues={{ remember: true }}
          preserve={false}
          autoComplete="off"
        >
          <Form.Item
            label="名称"
            name="username"
            validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入名称' },
              { min: 2, max: 15, message: '名称长度必须在2到15个字符之间' },
            ]}
          >
            <Input
              value={formData.username}
              onChange={(e) => setFormData({ ...formData, username: e.target.value })}
              autoComplete="off"
            />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            validateTrigger="onBlur"
            rules={[
              { required: true, message: '请输入密码' },
              { min: 6, max: 15, message: '密码长度必须在6到15个字符之间' },
            ]}
          >
            <Input.Password
              value={formData.password}
              onChange={(e) => setFormData({ ...formData, password: e.target.value })}
              autoComplete="off"
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}

export default Teacher
